package easyexcel.write.merge;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import easyexcel.write.merge.dto.RangeDto;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;
import java.util.Map;

/**
 * @author zwh
 * @date 2023-10-17 9:31
 */
public class BizMergeStrategy extends AbstractMergeStrategy {

    private Map<String, List<RangeDto>> rowMergeMap;
    private Map<String, List<RangeDto>> colMergeMap;
    private Sheet sheet;

    /**
     * 将要合并的行和列构成map传入构造函数，创建时会自用调用重写的merge方法
     *
     * @param rowMergeMap 需要合并的行，map的key是列的索引，list中是要合并的行索引（start：从第几行开始，end到第几行结束）
     * @param colMergeMap 需要合并的列，map的key是行的索引，list中是要合并的列索引（start：从第几列开始，end到第几列结束）
     */
    public BizMergeStrategy(Map<String, List<RangeDto>> rowMergeMap, Map<String, List<RangeDto>> colMergeMap) {
        this.rowMergeMap = rowMergeMap;
        this.colMergeMap = colMergeMap;
    }
    /**
     * 自定义合并规则
     */
    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        this.sheet = sheet;
        //这里判断根据需求更改，这里是从第三行第一列开始做判断
        if (cell.getRowIndex() == 2 && cell.getColumnIndex() == 0) {
            for (Map.Entry<String, List<RangeDto>> entry : rowMergeMap.entrySet()) {
                Integer columnIndex = Integer.valueOf(entry.getKey());
                for (RangeDto rowRange : entry.getValue()) {
                    //添加一个合并请求
                    sheet.addMergedRegionUnsafe(new CellRangeAddress(rowRange.getStart(),
                            rowRange.getEnd(), columnIndex, columnIndex));
                }
            }
            for (Map.Entry<String, List<RangeDto>> entry : colMergeMap.entrySet()) {
                Integer rowIndex = Integer.valueOf(entry.getKey());
                for (RangeDto colRange : entry.getValue()) {
                    //添加一个合并请求
                    sheet.addMergedRegionUnsafe(new CellRangeAddress(rowIndex,
                            rowIndex, colRange.getStart(), colRange.getEnd()));
                }
            }
        }
    }
}
